<template>
  <div class="pressure-heatmap-page">
    <!-- 顶部导航 -->
    <Navigation />
    
    <div class="main-layout">
      <!-- 左侧边栏 -->
      <aside class="sidebar">
        <div class="sidebar-header">
          <h2>智能瓷砖监控平台</h2>
        </div>
        
        <nav class="sidebar-nav">
          <div class="nav-section">
            <div class="section-header">
              <h3>数据监控</h3>
            </div>
            <div class="nav-items">
              <router-link 
                to="/data-monitoring/realtime" 
                class="nav-item" 
                :class="{ active: activeSection === 'realtime' }"
              >
                <div class="nav-icon realtime-icon"></div>
                <span>实时数据</span>
              </router-link>
              <router-link 
                to="/data-monitoring/history" 
                class="nav-item" 
                :class="{ active: activeSection === 'history' }"
              >
                <div class="nav-icon history-icon"></div>
                <span>历史数据</span>
              </router-link>
              <router-link 
                to="/data-monitoring/trend" 
                class="nav-item" 
                :class="{ active: activeSection === 'trend' }"
              >
                <div class="nav-icon trend-icon"></div>
                <span>趋势分析</span>
              </router-link>
              <router-link 
                to="/data-monitoring/pressure-heatmap" 
                class="nav-item" 
                :class="{ active: activeSection === 'heatmap' }"
              >
                <div class="nav-icon heatmap-icon"></div>
                <span>压力热图</span>
              </router-link>
            </div>
          </div>
        </nav>
      </aside>

      <!-- 主内容区域 -->
      <main class="main-content">
        <!-- 面包屑导航 -->
        <div class="breadcrumb">
          <span class="breadcrumb-item">数据监控</span>
          <span class="breadcrumb-separator">/</span>
          <span class="breadcrumb-item current">{{ currentSectionName }}</span>
        </div>

        <!-- 顶部控制栏 -->
        <div class="top-controls">
          <div class="datetime-picker">
            <div class="datetime-icon"></div>
            <span class="datetime-text">2023-11-28</span>
            <span class="time-text">14:30</span>
          </div>
          <button class="view-btn">查看</button>
        </div>

        <!-- 控制面板 -->
        <div class="control-panel">
          <div class="control-row">
            <div class="control-group">
              <label>区域选择</label>
              <select class="control-select">
                <option>全部区域</option>
                <option>区域A</option>
                <option>区域B</option>
                <option>区域C</option>
              </select>
            </div>
            
            <div class="control-group">
              <label>压力范围</label>
              <div class="pressure-range">
                <div class="range-slider"></div>
                <div class="range-handles">
                  <div class="range-handle left"></div>
                  <div class="range-handle right"></div>
                </div>
              </div>
            </div>
            
            <div class="control-group">
              <label>视图模式</label>
              <div class="view-toggle">
                <button class="toggle-btn active">2D</button>
                <button class="toggle-btn">3D</button>
              </div>
            </div>
            
            <div class="control-group">
              <label>刷新频率</label>
              <select class="control-select">
                <option>实时</option>
                <option>1分钟</option>
                <option>5分钟</option>
                <option>10分钟</option>
              </select>
            </div>
          </div>
          
          <div class="range-labels">
            <span class="range-label">0 kPa</span>
            <span class="range-label">8 kPa</span>
          </div>
        </div>

        <!-- 主要内容区域 -->
        <div class="content-grid">
          <!-- 压力热图 -->
          <div class="heatmap-section">
            <div class="section-header">
              <h3>瓷砖压力分布热图</h3>
            </div>
            <div class="heatmap-container">
              <EnhancedPressureHeatmap 
                :data="heatmapData" 
                :showGrid="showGrid"
                :showValues="showValues"
                :showCoordinates="showCoordinates"
                @cell-click="handleCellClick"
              />
            </div>
          </div>

          <!-- 右侧面板 -->
          <div class="side-panels">
            <!-- 热点分析 -->
            <HotspotAnalysis :hotspots="hotspotData" />
            
            <!-- 时间序列热图 -->
            <TimeSeriesHeatmap :timeData="timeSeriesData" />
          </div>
        </div>

        <!-- 历史数据对比 -->
        <HistoricalComparison :comparisonData="historicalData" />

        <!-- 底部控制栏 -->
        <div class="bottom-controls">
          <div class="display-options">
            <label class="checkbox-label">
              <input type="checkbox" v-model="showGrid" />
              <span class="checkbox-custom"></span>
              显示网格
            </label>
            <label class="checkbox-label">
              <input type="checkbox" v-model="showValues" />
              <span class="checkbox-custom"></span>
              显示数值
            </label>
            <label class="checkbox-label">
              <input type="checkbox" v-model="showCoordinates" />
              <span class="checkbox-custom"></span>
              显示坐标
            </label>
          </div>
          
          <div class="pressure-threshold">
            <span>压力阈值:</span>
            <div class="threshold-slider"></div>
          </div>
          
          <div class="action-buttons">
            <button class="action-btn">
              <div class="btn-icon export-icon"></div>
              导出报告
            </button>
            <button class="action-btn">
              <div class="btn-icon share-icon"></div>
              分享
            </button>
            <button class="action-btn">
              <div class="btn-icon print-icon"></div>
              打印
            </button>
          </div>
        </div>
      </main>
    </div>
  </div>
</template>

<script>
import Navigation from '../components/Navigation.vue'
import EnhancedPressureHeatmap from './components/EnhancedPressureHeatmap.vue'
import HotspotAnalysis from './components/HotspotAnalysis.vue'
import TimeSeriesHeatmap from './components/TimeSeriesHeatmap.vue'
import HistoricalComparison from './components/HistoricalComparison.vue'
import smartTileApi from '../api/smartTileApi.js'

export default {
  name: 'PressureHeatmapPage',
  components: {
    Navigation,
    EnhancedPressureHeatmap,
    HotspotAnalysis,
    TimeSeriesHeatmap,
    HistoricalComparison
  },
  data() {
    return {
      // 显示选项
      showGrid: true,
      showValues: true,
      showCoordinates: true,
      
      // 热图数据
      heatmapData: [],
      
      // 热点数据
      hotspotData: [
        {
          position: '区域A-5-5',
          pressure: '8',
          duration: '2小时39分',
          status: 'critical'
        },
        {
          position: '区域A-4-5',
          pressure: '7.8',
          duration: '2小时39分',
          status: 'critical'
        },
        {
          position: '区域A-6-5',
          pressure: '7.5',
          duration: '1小时43分',
          status: 'critical'
        },
        {
          position: '区域A-5-6',
          pressure: '7.2',
          duration: '2小时1分',
          status: 'critical'
        },
        {
          position: '区域A-3-5',
          pressure: '7.1',
          duration: '1小时20分',
          status: 'critical'
        }
      ],
      
      // 时间序列数据
      timeSeriesData: [
        { time: '12:00', intensity: 0.7 },
        { time: '13:00', intensity: 0.7 },
        { time: '14:00', intensity: 0.7 },
        { time: '15:00', intensity: 0.7 }
      ],
      
      // 历史对比数据
      historicalData: {
        currentHeatmap: this.generateHeatmapData(),
        historicalHeatmap: this.generateHeatmapData(0.8),
        maxChangeArea: '区域A-2-3',
        avgChangeRate: '+18.6%',
        abnormalGrowthAreas: [
          { area: '区域A-2-3', from: '7.4kPa', to: '5.9kPa', change: '+25%' },
          { area: '区域C-5-1', from: '6.8kPa', to: '5.5kPa', change: '+23%' },
          { area: '区域B-1-7', from: '6.3kPa', to: '5.2kPa', change: '+21%' }
        ]
      }
    }
  },
  computed: {
    activeSection() {
      // 根据路由元信息确定当前活动的侧边栏项
      if (this.$route.meta && this.$route.meta.activeSection) {
        return this.$route.meta.activeSection
      }
      
      // 根据路径判断
      const path = this.$route.path
      if (path.includes('/realtime')) return 'realtime'
      if (path.includes('/history')) return 'history'
      if (path.includes('/trend')) return 'trend'
      if (path.includes('/pressure-heatmap')) return 'heatmap'
      
      // 默认为压力热图
      return 'heatmap'
    },
    
    currentSectionName() {
      const sectionNames = {
        'realtime': '实时数据',
        'history': '历史数据',
        'trend': '趋势分析',
        'heatmap': '压力热图'
      }
      return sectionNames[this.activeSection] || '压力热图'
    }
  },
  mounted() {
    // 页面加载时获取真实数据
    this.loadRealTimeData()
    
    // 设置定时刷新，每5秒更新一次数据
    this.refreshTimer = setInterval(() => {
      this.loadRealTimeData()
    }, 5000)
  },
  
  beforeUnmount() {
    // 清除定时器
    if (this.refreshTimer) {
      clearInterval(this.refreshTimer)
    }
  },
  
  methods: {
    /**
     * 加载真实传感器数据
     */
    async loadRealTimeData() {
      try {
        const response = await smartTileApi.getRealSensorData()
        if (response && response.success && response.data && response.data.heatmap) {
          // 将3x7的真实数据转换为10x10格式以适配EnhancedPressureHeatmap组件
          this.heatmapData = this.convertToEnhancedFormat(response.data.heatmap)
          console.log('压力热图数据已更新:', new Date().toLocaleTimeString())
        }
      } catch (error) {
        console.warn('加载真实传感器数据失败，使用模拟数据:', error)
        // 失败时使用模拟数据
        this.heatmapData = this.generateHeatmapData()
      }
    },
    
    /**
     * 将3x7的真实数据转换为10x10格式
     * @param {Array} realData - 3x7的真实传感器数据
     * @returns {Array} 10x10格式的热图数据
     */
    convertToEnhancedFormat(realData) {
      const data = []
      for (let y = 1; y <= 10; y++) {
        const row = []
        for (let x = 1; x <= 10; x++) {
          // 在10x10网格中心放置3x7的真实数据
          // 真实数据区域：行4-6，列2-8
          if (y >= 4 && y <= 6 && x >= 2 && x <= 8) {
            const realRow = y - 4  // 0-2
            const realCol = x - 2   // 0-6
            if (realData[realRow] && realData[realRow][realCol]) {
              const realCell = realData[realRow][realCol]
              row.push({
                x,
                y,
                pressure: realCell.pressure,
                level: realCell.level,
                position: `X${x}-Y${y}`
              })
            } else {
              // 如果真实数据不存在，使用默认值
              row.push({
                x,
                y,
                pressure: '0',
                level: 'normal',
                position: `X${x}-Y${y}`
              })
            }
          } else {
            // 非真实数据区域，使用低压力值
            row.push({
              x,
              y,
              pressure: '0',
              level: 'normal',
              position: `X${x}-Y${y}`
            })
          }
        }
        data.push(row)
      }
      return data
    },
    
    generateHeatmapData(intensityMultiplier = 1) {
      const data = []
      for (let y = 1; y <= 10; y++) {
        const row = []
        for (let x = 1; x <= 10; x++) {
          const pressure = Math.random() * 8 * intensityMultiplier
          let level = 'normal'
          if (pressure > 6) level = 'critical'
          else if (pressure > 4) level = 'warning'
          
          row.push({
            x,
            y,
            pressure: pressure.toFixed(1),
            level,
            position: `X${x}-Y${y}`
          })
        }
        data.push(row)
      }
      return data
    },
    
    handleCellClick(cell) {
      console.log('Cell clicked:', cell)
      // 处理单元格点击事件
    }
  }
}
</script>

<style scoped>
.pressure-heatmap-page {
  min-height: 100vh;
  background: #F5F5F5;
  font-family: 'Inter', sans-serif;
}

/* 主布局 */
.main-layout {
  display: flex;
  min-height: calc(100vh - 64px);
}

/* 左侧边栏 */
.sidebar {
  width: 220px;
  background: #FFFFFF;
  border-right: 1px solid #E5E7EB;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 17.5px 24px;
  border-bottom: 1px solid #E5E7EB;
}

.sidebar-header h2 {
  font-size: 18px;
  font-weight: 700;
  color: #000000;
  margin: 0;
  line-height: 28px;
}

.sidebar-nav {
  padding: 18px 16px;
  flex: 1;
}

.nav-section {
  margin-bottom: 12px;
}

.section-header {
  padding: 16px 0 17px;
  border-bottom: 1px solid #E5E7EB;
  margin-bottom: 12px;
}

.section-header h3 {
  font-size: 16px;
  font-weight: 700;
  color: #000000;
  margin: 0;
  line-height: 24px;
}

.nav-items {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.nav-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  border-radius: 8px;
  color: #4B5563;
  cursor: pointer;
  transition: all 0.2s;
  font-size: 16px;
  font-weight: 500;
  line-height: 24px;
}

.nav-item.active {
  background: #E6F4FF;
  color: #1677FF;
  border-right: 2px solid #1677FF;
}

.nav-item:hover:not(.active) {
  background: #F5F5F5;
}

.nav-icon {
  width: 16px;
  height: 16px;
  background-size: contain;
  background-repeat: no-repeat;
}

.realtime-icon {
  background-image: url('https://miaoduo.fbcontent.cn/private/resource/image/19918fa02f8f389-649432e6-65c6-4ac6-9d5a-2f95750b48e0.svg');
}

.history-icon {
  background-image: url('https://miaoduo.fbcontent.cn/private/resource/image/1991943be494943-6d4ab801-859d-4a43-92da-c6b73e808d58.svg');
}

.trend-icon {
  background-image: url('https://miaoduo.fbcontent.cn/private/resource/image/19918fa02f8a99d-52928a09-cb24-4968-a08f-3783cb645325.svg');
}

.heatmap-icon {
  background-image: url('https://miaoduo.fbcontent.cn/private/resource/image/1991943be4aa9fe-8fe5702e-3093-4047-9942-ef97b302db6b.svg');
}

/* 主内容区域 */
.main-content {
  flex: 1;
  padding: 24px;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

/* 面包屑导航 */
.breadcrumb {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  line-height: 20px;
  margin-bottom: 16px;
}

.breadcrumb-item {
  color: #6B7280;
}

.breadcrumb-item.current {
  color: #1F2937;
}

.breadcrumb-separator {
  color: #6B7280;
}

/* 顶部控制栏 */
.top-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.datetime-picker {
  display: flex;
  align-items: center;
  gap: 8px;
  background: #FFFFFF;
  border: 1px solid #D1D5DB;
  border-radius: 6px;
  padding: 7px 13px 7px 13px;
}

.datetime-icon {
  width: 16px;
  height: 16px;
  background-image: url('https://miaoduo.fbcontent.cn/private/resource/image/19918fa02f8744c-577a2894-e658-4098-96e9-aaa3e62fb9ee.svg');
  background-size: contain;
  background-repeat: no-repeat;
}

.datetime-text {
  color: #000000;
  font-size: 14px;
  line-height: 20px;
}

.time-text {
  color: #9CA3AF;
  font-size: 16px;
  line-height: 24px;
}

.view-btn {
  background: #1677FF;
  border: none;
  border-radius: 6px;
  color: #FFFFFF;
  font-size: 14px;
  line-height: 20px;
  padding: 6px 16px;
  cursor: pointer;
  transition: all 0.2s;
}

.view-btn:hover {
  background: #0958d9;
}

/* 控制面板 */
.control-panel {
  background: #FFFFFF;
  box-shadow: 0px 1px 2px 0px rgba(0, 0, 0, 0.05);
  border-radius: 6px;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.control-row {
  display: flex;
  gap: 24px;
  align-items: flex-end;
}

.control-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
  flex: 1;
}

.control-group label {
  color: #6B7280;
  font-size: 14px;
  line-height: 20px;
}

.control-select {
  background: #EFEFEF;
  border: 1px solid #D1D5DB;
  border-radius: 6px;
  padding: 6px 12px;
  font-size: 14px;
  line-height: 22px;
  color: #000000;
  cursor: pointer;
}

.pressure-range {
  position: relative;
  height: 34px;
  display: flex;
  align-items: center;
}

.range-slider {
  width: 100%;
  height: 4px;
  background: linear-gradient(90deg, #1677FF 0%, #FAAD14 50%, #FF4D4F 100%);
  border-radius: 2px;
}

.range-handles {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  width: 100%;
  display: flex;
  justify-content: space-between;
  padding: 0 8px;
}

.range-handle {
  width: 16px;
  height: 16px;
  background: #FFFFFF;
  border: 2px solid #1677FF;
  border-radius: 50%;
  cursor: pointer;
}

.view-toggle {
  display: flex;
  border: 1px solid #D1D5DB;
  border-radius: 6px;
  overflow: hidden;
}

.toggle-btn {
  background: #FFFFFF;
  border: none;
  padding: 6px 56px;
  font-size: 14px;
  color: #4B5563;
  cursor: pointer;
  transition: all 0.2s;
  flex: 1;
}

.toggle-btn.active {
  background: #1677FF;
  color: #FFFFFF;
}

.range-labels {
  display: flex;
  justify-content: space-between;
  margin-left: 289px;
  margin-right: 289px;
  margin-top: 8px;
}

.range-label {
  color: #6B7280;
  font-size: 12px;
  line-height: 16px;
}

/* 内容网格 */
.content-grid {
  display: flex;
  gap: 24px;
}

/* 热图区域 */
.heatmap-section {
  flex: 1;
  background: #FFFFFF;
  box-shadow: 0px 1px 2px 0px rgba(0, 0, 0, 0.05);
  border-radius: 6px;
  overflow: hidden;
}

.section-header {
  padding: 20px;
  border-bottom: 1px solid #F0F0F0;
}

.section-header h3 {
  font-size: 16px;
  font-weight: 600;
  color: #000000;
  margin: 0;
  line-height: 24px;
}

.heatmap-container {
  padding: 20px;
}

/* 右侧面板 */
.side-panels {
  width: 275px;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

/* 底部控制栏 */
.bottom-controls {
  background: #FFFFFF;
  box-shadow: 0px 1px 2px 0px rgba(0, 0, 0, 0.05);
  border-radius: 6px;
  padding: 16px;
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.display-options {
  display: flex;
  gap: 16px;
  align-items: center;
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  line-height: 20px;
  color: #000000;
  cursor: pointer;
}

.checkbox-label input[type="checkbox"] {
  display: none;
}

.checkbox-custom {
  width: 16px;
  height: 16px;
  background: #2A72FB;
  border-radius: 2px;
  position: relative;
}

.checkbox-custom::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 16px;
  height: 16px;
  background-image: url('https://miaoduo.fbcontent.cn/private/resource/image/1991943be4b90c5-57b1cd1d-2b73-46e9-a513-ad52373c82b0.svg');
  background-size: contain;
  background-repeat: no-repeat;
}

.pressure-threshold {
  display: flex;
  align-items: center;
  gap: 16px;
  color: #000000;
  font-size: 14px;
  line-height: 20px;
  margin-left: auto;
  margin-right: 16px;
}

.threshold-slider {
  width: 150px;
  height: 4px;
  background: linear-gradient(90deg, #1677FF 0%, #FAAD14 50%, #FF4D4F 100%);
  border-radius: 2px;
  position: relative;
}

.threshold-slider::after {
  content: '';
  position: absolute;
  top: 50%;
  right: 0;
  transform: translateY(-50%);
  width: 16px;
  height: 16px;
  background: #FFFFFF;
  border: 2px solid #1677FF;
  border-radius: 50%;
}

.action-buttons {
  display: flex;
  gap: 4px;
}

.action-btn {
  background: #FFFFFF;
  border: 1px solid #D1D5DB;
  border-radius: 6px;
  padding: 7px 13px;
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  line-height: 20px;
  color: #000000;
  cursor: pointer;
  transition: all 0.2s;
}

.action-btn:hover {
  border-color: #1677FF;
  color: #1677FF;
}

.btn-icon {
  width: 16px;
  height: 16px;
  background-size: contain;
  background-repeat: no-repeat;
}

.export-icon {
  background-image: url('https://miaoduo.fbcontent.cn/private/resource/image/1991943be4b43b9-ea782086-ca06-4c74-8a5b-f72e317856d9.svg');
}

.share-icon {
  background-image: url('https://miaoduo.fbcontent.cn/private/resource/image/1991943be4b21ad-61be372b-dfec-44d5-ae2d-bc883cbf8aaf.svg');
}

.print-icon {
  background-image: url('https://miaoduo.fbcontent.cn/private/resource/image/1991943be4b3b19-0ce50737-82a9-476d-98e8-9ddbb884f2eb.svg');
}

/* 响应式设计 */
@media (max-width: 1400px) {
  .content-grid {
    flex-direction: column;
  }
  
  .side-panels {
    width: 100%;
    flex-direction: row;
  }
}

@media (max-width: 992px) {
  .main-layout {
    flex-direction: column;
  }
  
  .sidebar {
    width: 100%;
    order: 2;
  }
  
  .main-content {
    order: 1;
  }
  
  .control-row {
    flex-direction: column;
    gap: 16px;
  }
  
  .bottom-controls {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;
  }
  
  .pressure-threshold {
    margin-left: 0;
    margin-right: 0;
    justify-content: center;
  }
}

@media (max-width: 768px) {
  .main-content {
    padding: 12px;
    gap: 16px;
  }
  
  .side-panels {
    flex-direction: column;
  }
  
  .display-options {
    flex-direction: column;
    gap: 8px;
  }
  
  .action-buttons {
    flex-direction: column;
    width: 100%;
  }
}
</style>
